/**
 * 图片缓存服务
 * 用于将外部图片下载并保存到本地，避免重复请求外部资源
 */

interface CacheInfo {
  originalUrl: string
  localUrl: string
  cached: boolean
  timestamp: number
}

class ImageCacheService {
  private cache = new Map<string, CacheInfo>()
  private readonly CACHE_EXPIRY = 7 * 24 * 60 * 60 * 1000 // 7天过期

  /**
   * 获取图片URL，如果已缓存则返回本地URL，否则下载并缓存
   */
  async getImageUrl(originalUrl: string): Promise<string> {
    if (!originalUrl) return ''
    
    // 检查缓存
    const cacheKey = this.getCacheKey(originalUrl)
    const cached = this.cache.get(cacheKey)
    
    if (cached && this.isCacheValid(cached)) {
      return cached.localUrl
    }
    
    // 下载并缓存图片
    try {
      const localUrl = await this.downloadAndCache(originalUrl)
      this.cache.set(cacheKey, {
        originalUrl,
        localUrl,
        cached: true,
        timestamp: Date.now()
      })
      return localUrl
    } catch (error) {
      console.error('图片缓存失败:', error)
      return originalUrl // 失败时返回原始URL
    }
  }

  /**
   * 下载图片并保存到本地
   */
  private async downloadAndCache(url: string): Promise<string> {
    try {
      // 创建唯一的文件名
      const filename = this.generateFilename(url)
      const response = await fetch(url)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const blob = await response.blob()
      
      // 将blob转换为base64 URL
      const reader = new FileReader()
      return new Promise((resolve, reject) => {
        reader.onload = () => {
          resolve(reader.result as string)
        }
        reader.onerror = reject
        reader.readAsDataURL(blob)
      })
    } catch (error) {
      console.error('下载图片失败:', error)
      throw error
    }
  }

  /**
   * 生成缓存键
   */
  private getCacheKey(url: string): string {
    try {
      return new URL(url).href
    } catch {
      return url
    }
  }

  /**
   * 生成文件名
   */
  private generateFilename(url: string): string {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    const ext = pathname.split('.').pop() || 'jpg'
    const hash = this.simpleHash(url)
    return `${hash}.${ext}`
  }

  /**
   * 简单的哈希函数
   */
  private simpleHash(str: string): string {
    let hash = 0
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // 转换为32位整数
    }
    return Math.abs(hash).toString(36)
  }

  /**
   * 检查缓存是否有效
   */
  private isCacheValid(cacheInfo: CacheInfo): boolean {
    return Date.now() - cacheInfo.timestamp < this.CACHE_EXPIRY
  }

  /**
   * 清除过期缓存
   */
  clearExpiredCache(): void {
    const now = Date.now()
    for (const [key, cacheInfo] of this.cache.entries()) {
      if (now - cacheInfo.timestamp >= this.CACHE_EXPIRY) {
        this.cache.delete(key)
      }
    }
  }

  /**
   * 获取缓存统计信息
   */
  getCacheStats(): { total: number; valid: number; expired: number } {
    const now = Date.now()
    let valid = 0
    let expired = 0
    
    for (const cacheInfo of this.cache.values()) {
      if (now - cacheInfo.timestamp < this.CACHE_EXPIRY) {
        valid++
      } else {
        expired++
      }
    }
    
    return {
      total: this.cache.size,
      valid,
      expired
    }
  }
}

// 创建单例实例
export const imageCacheService = new ImageCacheService()

// 定期清理过期缓存
setInterval(() => {
  imageCacheService.clearExpiredCache()
}, 60 * 60 * 1000) // 每小时清理一次

export default imageCacheService
